package com.xkstream.client.ui;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wangjing.permission.annotations.PermissionsRequestSync;
import com.xkstream.client.R;
import com.xkstream.client.application.Application;
import com.xkstream.client.appmanager.AppManager;
import com.xkstream.client.base.BaseActivity;
import com.xkstream.client.base.BaseData;
import com.xkstream.client.common.AppConfig;
import com.xkstream.client.common.CommonDialog;
import com.xkstream.client.entity.FirVersion;
import com.xkstream.client.entity.Game;
import com.xkstream.client.entity.User;
import com.xkstream.client.entity.kt.MessagesData;
import com.xkstream.client.presenter.kt.AnchorStateContract;
import com.xkstream.client.presenter.kt.AnchorStatePresenter;
import com.xkstream.client.rx.Rxbus;
import com.xkstream.client.service.DownloadService;
import com.xkstream.client.service.JPushUtil;
import com.xkstream.client.ui.live.LiveRoomActivity;
import com.xkstream.client.ui.live.LiveRoomActivity_V2;
import com.xkstream.client.utils.AsyncImage;
import com.xkstream.client.utils.DeviceUtils;
import com.xkstream.client.view.CircleImageView;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.CompositeDisposable;


/**
 * Created by xiaoyi on 2017-9-26.
 * 主播状态
 */

public class AnchorStateActivity extends BaseActivity<AnchorStateContract.Presenter>
        implements AnchorStateContract.View {


    @BindView(R.id.circle_outer)
    CircleImageView circleOuter;
    @BindView(R.id.circle_middle)
    CircleImageView circleMiddle;
    @BindView(R.id.circle_inner)
    CircleImageView circleInner;

    @BindView(R.id.tvNickname)
    TextView tvNickName;

    ScaleAnimation anim;
    Animation outer;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.ivMsgPoint)
    ImageView ivMsgPoint;
    @BindView(R.id.ivHeader)
    CircleImageView ivHeader;
    @BindView(R.id.tvMyZone)
    TextView tvMyZone;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tv_state_caption)
    TextView tvStateCaption;
    @BindView(R.id.tv_Settings)
    TextView tvSettings;
    @BindView(R.id.tv_gains)
    TextView tvGains;
    @BindView(R.id.tv_help)
    TextView tvHelp;

    User user;

    private long lastClickBackTime = -1;
    private static final int QUIT_CONFIRM_TIME = 3000;

    private CompositeDisposable disposable = new CompositeDisposable();

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_anchor_state);
        ButterKnife.bind(this);
        presenter = new AnchorStatePresenter(this);
        user = Application.getUser();
        int state = user.getAnchor().getAudit_statu();
        initState(state);
        registerUserWatcher();
        if (user.getExt_info() == null || TextUtils.isEmpty(user.getExt_info().getNickname())) {
            tvNickName.setText("");
        } else {
            tvNickName.setText(user.getExt_info().getNickname());
            AsyncImage.loadPhoto(this, user.getExt_info().getHead_icon(), ivHeader);
        }
        setEnable();
        JPushUtil jpushUtil = JPushUtil.getInstance();
        if (!TextUtils.isEmpty(Application.getUser().getUser_code())) {
//            jpushUtil.setAliasWithTags(mContext.getResources().getString(R.string.alias) + user.getId(), JPushUtil.initTags(user));
            if (AppConfig.isTest()) {
                jpushUtil.setAliasWithTags(Application.getUser().getUser_code(), JPushUtil.initTags());
            } else {
                jpushUtil.setAliasWithTags(Application.getUser().getUser_code(), JPushUtil.initTags());
            }
        }
        presenter.checkVersion();
    }

    private void setEnable() {
        if (user.getAnchor().getAudit_statu() != 2) {
            tvSettings.setEnabled(false);
            tvGains.setEnabled(false);
            tvMyZone.setEnabled(false);
        } else {
            tvSettings.setEnabled(true);
            tvMyZone.setEnabled(true);
            tvGains.setEnabled(true);
        }
    }

    private void registerUserWatcher() {
        disposable.add(Rxbus.getDefault().register(User.class)
                .subscribe((user) -> {
                    this.user = user;
                    initState(user.getAnchor().getAudit_statu());
                }));
    }


    private void initState(int state) {
        switch (state) {
            case 2:
                setAnim(true);
                tvState.setText(R.string.start_live_v2);
                tvStateCaption.setText(R.string.caption_start);
                tvState.setOnClickListener((v) -> {
                    anchorOn();
                   /* Intent intent = new Intent();
                    intent.putExtra("gameType", "4");
                    intent.setClass(this, LiveRoomActivity.class);
                    startActivity(intent);*/
                });
                break;
            case 1:
                setAnim(false);
                setCircleColorGray();
                tvState.setText(R.string.wait_review);
                tvStateCaption.setText(R.string.caption_wait_review);
                break;
            case 0:
                setAnim(true);
                tvState.setText(R.string.submit_apply);
                tvStateCaption.setText(R.string.caption_submit_apply);
                tvState.setOnClickListener((v) -> {
                    jumpToActivity(AnchorApplyActivity.class);
                });
                break;
            case 3:
                setAnim(true);
                tvState.setText(R.string.reapply);
                tvStateCaption.setText(R.string.caption_resubmit);
                tvState.setOnClickListener((v) -> {
                    jumpToActivity(AnchorApplyActivity.class);
                });
                break;
        }
    }

    private void setAnim(boolean play) {
        if (play) {
            anim = (ScaleAnimation) AnimationUtils.loadAnimation(this, R.anim.anim_scale);
            anim.setRepeatMode(Animation.REVERSE);
            anim.setRepeatCount(Integer.MAX_VALUE);

//        circleInner.startAnimation(anim);
//        circleOuter.startAnimation(anim);
            circleMiddle.startAnimation(anim);
            outer = AnimationUtils.loadAnimation(this, R.anim.anim_scale_outer);
            outer.setRepeatMode(Animation.REVERSE);
            outer.setRepeatCount(Integer.MAX_VALUE);
            circleOuter.startAnimation(outer);
        } else {
            if (anim != null) {
                anim.cancel();
            }
            if (outer != null) {
                outer.cancel();
            }
        }
    }

    private void setCircleColorGray() {
        circleOuter.setImageResource(R.drawable.circle_outer_gray);
        circleMiddle.setImageResource(R.drawable.circle_middle_gray);
        circleInner.setImageResource(R.drawable.circle_inner_gray);
    }

    @OnClick({R.id.iv_message, R.id.tvMyZone, R.id.tv_Settings, R.id.tv_gains, R.id.tv_help})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_message:
                jumpToActivity(MessageActivity.class);
                break;
            case R.id.tvMyZone:
                jumpToActivity(MyZoneActivity.class);
                break;
            case R.id.tv_Settings:
                //jumpToActivity(LiveSettingActivity.class);
                break;
            case R.id.tv_gains:
                jumpToActivity(GainsRecorderActivity.class);
                break;
            case R.id.tv_help:
                jumpToActivity(HelpActivity.class);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUnreadMessage();
    }

    private void getUnreadMessage() {
        User user = Application.getUser();
        Map<String, String> params = new HashMap<>();
        params.put("user_code", user.getUser_code());
        params.put("status", "0");
        presenter.getUnreadMessage(params);
    }

    @Override
    public void showUnReadMessage(@NotNull BaseData<MessagesData> data) {
        if (data.getData() != null) {
            if (data.getData().getTotal() != null && data.getData().getTotal() > 0) {
                ivMsgPoint.setVisibility(View.VISIBLE);
            } else {
                ivMsgPoint.setVisibility(View.GONE);
            }
        } else {
            ivMsgPoint.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(@Nullable String message) {
        showTopTips(message);
    }

    @Override
    public void setPresenter(AnchorStateContract.Presenter presenter) {
        this.presenter = presenter;
    }


    @Override
    public void showAnchorOnResult(@NotNull BaseData data) {
        if (data.getCode() == 1) {
            Intent intent = new Intent();
            // intent.putExtra("gameType", data.getData().getGame_type());
            intent.setClass(this, LiveRoomActivity_V2.class);
            startActivity(intent);
        } else {
            showTopTips(data.getMsg());
        }
    }

    @Override
    public void showFirVersion(@Nullable FirVersion version) {
        int localVersion = Integer.parseInt(DeviceUtils.getVersionCode(this));
        int latestVersion = Integer.parseInt(version.getVersion());
        if (latestVersion > localVersion) {
            showUpdateDialog(version);
        }
    }

    private void showUpdateDialog(FirVersion version) {
        CommonDialog dialog = new CommonDialog(this);
        dialog.setTitle(getResources().getString(R.string.update_hint));
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setSingleButton();
        dialog.setListener(() -> {
            Intent it = new Intent(AnchorStateActivity.this, DownloadService.class);
            it.putExtra("apkUrl", version.getInstallUrl());
            startService(it);
            ServiceConnection conn = new ServiceConnection() {
                @Override
                public void onServiceDisconnected(ComponentName name) {

                }

                @Override
                public void onServiceConnected(ComponentName name, IBinder service) {

                }
            };
            bindService(it, conn, BIND_AUTO_CREATE);

            tvStateCaption.setText(R.string.updating);
            tvState.setEnabled(false);
        });
        dialog.show();
    }

    private void anchorOn() {
        Map<String, String> params = new HashMap<>();
        params.put("anchor_user_code", Application.getUser().getUser_code());
        params.put("anchor_status", "1");
        params.put("anchor_title", user.getExt_info().getNickname());
//        params.put("game_type", "2");
        presenter.anchorOn(params);
    }

    @Override
    public void onBackPressed() {
        long curTime = System.currentTimeMillis();
        if ((curTime - lastClickBackTime) >= QUIT_CONFIRM_TIME) {
            lastClickBackTime = curTime;
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
        } else {
            AppManager.getAppManager().AppExit(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposable.clear();
    }
}
